package com.gmail.blackdog1987.carcare.service.impl;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.gmail.blackdog1987.carcare.dao.SmsDao;
import com.gmail.blackdog1987.carcare.entity.TSms;
import com.gmail.blackdog1987.carcare.service.SmsService;

@Service("smsService")
public class SmsServiceImpl implements SmsService {

	private static final String ACCOUNT = "txct0701";
	private static final String PWD = "aa18911201510";
	private static final String ID = "3269";
	private static final String URL = "http://xtx.telhk.cn:8888/sms.aspx";

	@Autowired
	private SmsDao smsDao;

	public void doSendSMS() {
		Map<String, Object> filter = new HashMap<String, Object>();
		Map<String, Object> sort = new HashMap<String, Object>();
		filter.put("status", 0);
		filter.put("failuretimes<", 3);
		List<TSms> smss = smsDao.find(filter, sort);
		for (TSms sms : smss) {
			try {
				Map<String, String> params = new LinkedHashMap<String, String>();
				params.put("userid", ID);
				params.put("account", ACCOUNT);
				params.put("password", PWD);
				params.put("mobile", sms.getPhone());
				params.put("content", sms.getContent()+"【车拉丁】");
				params.put("action", "send");
				params.put("checkcontent", "0");
				params.put("taskName", "msg send");
				params.put("countnumber", "1");
				params.put("mobilenumber", "1");
				params.put("telephonenumber", "0");
				
				String resp = doPost(URL, params);
				
				Document document = DocumentHelper.parseText(resp);
				Element root = document.getRootElement();
				if (root == null || root.element("returnstatus")==null || !root.element("returnstatus").getText().equals("Success")){
					sms.setFailuretimes(sms.getFailuretimes()+1);
				}else{
					sms.setStatus(1);
				}
			} catch (Exception ex) {
				ex.printStackTrace();
			}
		}
		if(smss!=null&&smss.size()>0){
			smsDao.saveAll(smss);
		}
	}

	/**
	 * 执行一个HTTP POST请求，返回请求响应的HTML
	 * 
	 * @param url
	 *            请求的URL地址
	 * @param params
	 *            请求的查询参数,可以为null
	 * @return 返回请求响应的HTML
	 */
	private static String doPost(String url, Map<String, String> params) {
		String response = null;
		HttpClient client = new HttpClient();
		PostMethod postMethod = new PostMethod(url);
		postMethod.getParams().setParameter(
				HttpMethodParams.HTTP_CONTENT_CHARSET, "utf-8");

		// 设置Post数据
		if (!params.isEmpty()) {
			int i = 0;
			NameValuePair[] data = new NameValuePair[params.size()];
			for (Entry<String, String> entry : params.entrySet()) {
				data[i] = new NameValuePair(entry.getKey(), entry.getValue());
				i++;
			}
			postMethod.setRequestBody(data);
		}
		try {
			client.executeMethod(postMethod);
			if (postMethod.getStatusCode() == HttpStatus.SC_OK) {
				response = postMethod.getResponseBodyAsString();
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			postMethod.releaseConnection();
		}
		return response;
	}

}
